import express from 'express';
import session from "express-session";
import { chatStream } from './chatStream';
import { ChatSession } from './ChatSession';
async function main() {
 

  let currentUsage={current:{}};
  const stream = chatStream('请简单的回复苹果两个字，不要说别的',currentUsage);

 
  try {
    for await (const chunk of stream) {
      console.log(chunk);
    }
  } finally {
    const finalUsage = await stream.next();
    console.log('Usage:', finalUsage.value,currentUsage.current);
  }
}

main();
const app = express();
const port = 3000;

// 解析请求体中的 JSON 数据
app.use(express.json());
const userId="cc";

app.get('/chats', async (req, res) => {
  const userId = req.session.userId;
  if (!userId) {
    return res.status(401).json({ error: '未登录' });
  }
  try {
    const sessions = await ChatSession.getSessionByUserId(userId);
    res.json(sessions);
  } catch (error) {
    console.error('获取会话列表失败:', error);
    res.status(500).json({ error: '获取会话列表失败' });
  }
})
app.post('/chat', async (req, res) => {
  const userId = req.session.userId;
  if (!userId) {
    return res.status(401).json({ error: '未登录' });
  }

  const { message } = req.body;
  if (!message) {
    return res.status(400).json({ error: '消息不能为空' });
  }

  try {
    const session = await ChatSession.create({
      userId,
      title: message.substring(0, 50),
      createdAt: new Date(),
      lastActive: new Date()
    });

    let currentUsage = { current: {} };
    const stream = chatStream(message, currentUsage);
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    try {
      for await (const chunk of stream) {
        res.write(`data: ${JSON.stringify(chunk)}\n\n`);
      }
    } finally {
      res.end();
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ error: '发送消息失败' });
  }
});

app.delete('/chats/:sessionId', async (req, res) => {
  const userId = req.session.userId;
  if (!userId) {
    return res.status(401).json({ error: '未登录' });
  }

  const { sessionId } = req.params;
  try {
    await ChatSession.delete({ id: sessionId, userId });
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除会话失败:', error);
    res.status(500).json({ error: '删除会话失败' });
  }
});
app.get("signin",(req,res)=>{
  req.session.userId=userId;
  res.send("signin");
})
app.get("/",(req,res)=>{
  res.send("hello world");
})

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
}))

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
